from PySide6.QtWidgets import QApplication, QComboBox, QVBoxLayout, QWidget

import sys, os
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
from ui.Ui_trans import Ui_form

class MyWindow(QWidget, Ui_form):
    def __init__(self) -> None:
        super().__init__()
        self.setupUi(self)
        
        # 0. 配置数据字典
        self.type_detail_dict = {
            'length': {'米': 100, '千米': 1000 * 100, '厘米': 1, '分米': 10,},
            'weight': {'克': 1, '千克': 1000, '斤': 500},
            'time': {'小时': 60 * 60, '分钟': 60, '秒': 1, '毫秒': 1e-3, '微秒': 1e-6, '纳秒':1e-9},
        }
        self.type_dict = {
            '长度': self.type_detail_dict['length'], 
            '重量': self.type_detail_dict['weight'], 
            '时间': self.type_detail_dict['time'],
        }
        
        # 1. ComboBox 下拉框联动效果初始化
        self.dataTypeCombox.addItems(self.type_dict.keys())
        
        self.dataTypeCombox.currentTextChanged.connect(self.dictTypeChanged)
        self.dataTypeCombox.setCurrentText('时间')
        
        # 2. 绑定事件
        '''
        # 2.1 [LineEdit 输入栏]的完成输入事件: 使用textChanged事件 (此时可以直接获取变动后的内容，但每次输入都会触发函数)
        self.oneInputEditLine.textChanged.connect(self.textChanged)
        self.twoInputEditLine.textChanged.connect(self.textChanged)
        '''
        # 2.1 [LineEdit 输入栏]的完成输入事件：使用editingFinished事件（此时需要手动获取变动后的内容，但只有在输入完成后才会触发）
        self.oneInputEditLine.editingFinished.connect(self.editingFinished)
        self.twoInputEditLine.editingFinished.connect(self.editingFinished)
        
        # 2.2 [ComboBox 下拉框]的单位切换事件
        self.oneInputCombox.currentTextChanged.connect(self.dictDetailTypeChanged)
        self.twoInputCombox.currentTextChanged.connect(self.dictDetailTypeChanged)
      
    def dictTypeChanged(self):
        self.dictTypeChangingFlag = True
        self.oneInputCombox.clear()
        self.twoInputCombox.clear()
        current_data_type = self.dataTypeCombox.currentText()
        self.oneInputCombox.addItems(self.type_dict[current_data_type].keys())
        self.oneInputCombox.setCurrentIndex(0)
        self.twoInputCombox.addItems(self.type_dict[current_data_type].keys())
        self.twoInputCombox.setCurrentIndex(1)
        self.dictTypeChangingFlag = False
        # 变动后自动计算一次结果
        self.calculate(self.oneInputEditLine)

    def textChanged(self, text):
        sender = window.sender()
        # print(sender, text)
        self.calculate(sender)
        
    def editingFinished(self):
        sender = window.sender()
        if hasattr(sender, 'last_val') and sender.last_val == sender.text():
            print('值未改变，跳过计算') 
            return
        sender.last_val = sender.text()
        # print(sender, sender.text())
        self.calculate(sender)
    
    def dictDetailTypeChanged(self):
        # 当字典类型再变化的时候，跳过计算的触发
        if self.dictTypeChangingFlag:
            return
        '''
        转换单位明细类型调整后，重新计算结果，记得要错位;
        这里为了避免交互混乱，默认调整下拉框的时候，变化的值都为第二个输入框的
        '''
        sender = window.sender()
        from_line = self.oneInputEditLine
        # if sender == self.oneInputCombox:
        #     from_line = self.twoInputEditLine
        # else:
        #     from_line = self.oneInputEditLine
        self.calculate(from_line)
        
    def calculate(self, fromLine=None):
        if not fromLine or fromLine.text() == '':
            return
        from_val = fromLine.text()
        
        one_type = self.oneInputCombox.currentText()
        two_type = self.twoInputCombox.currentText()
        current_data_type = self.dataTypeCombox.currentText()
        
        if fromLine == self.oneInputEditLine or fromLine == self.oneInputCombox:
            print(f'第1行输入')
            from_type = one_type
            to_type = two_type
            to_lineEdit = self.twoInputEditLine
        elif fromLine == self.twoInputEditLine or fromLine == self.twoInputCombox:
            print(f'第2行输入')
            from_type = two_type
            to_type = one_type
            to_lineEdit = self.oneInputEditLine
        else:
            print(f'未知的触发按键: {fromLine}')
            return
        
        # 先换算出标准化的值
        standardization = float(from_val) * self.type_dict[current_data_type][from_type]
        # 再根据标准化的值，除以转换类型的单位即可
        result = standardization / self.type_dict[current_data_type][to_type]
        if len(str(result)) > 2:
            if str(result)[-2:] == '.0':
                result = str(result)[:-2]
            elif '.' in str(result):
                result = round(result, 6)
        
        self.originDataLabel.setText(f'{from_val} {from_type} =')
        self.transDataLabel.setText(f'{result} {to_type}')
        to_lineEdit.setText(f'{result}')
        to_lineEdit.last_val = f'{result}'
        
        print(f'计算结果：{result}')

if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MyWindow()
    window.show()

    app.exec()